﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AlarmManagePlatform.Forms
{
    public partial class AlarmInstrumentFrom : RelationsLMP.Control.Form.MetroDemoForms
    {
        public Model.DB.tb_AlarminstrumentInfo AlarminstrumentInfo { get; set; }
        private UC.ComboBox.SubmitUnit _CmbSubmitUnit;
        private UC.ComboBox.Manufacturer _CmbManufacturer;

        private UC.SelectImage SelectImage;
        public AlarmInstrumentFrom()
        {
            InitializeComponent();
            InitControls();
            txtInstrumentName.Focus();

            AlarminstrumentInfo = new Model.DB.tb_AlarminstrumentInfo();
        }


        public void ModifyInfo(Model.DB.tb_AlarminstrumentInfo temp)
        {
            AlarminstrumentInfo.InstrumentId = temp.InstrumentId;
            AlarminstrumentInfo.FactoryNumber = temp.FactoryNumber;

            txtInstrumentName.Text = temp.InstrumentName;
            txtFactoryNumber.Text = temp.FactoryNumber;
            txtModel.Text = temp.Model;
            txtContractNo.Text = temp.ContractNo;
            txtLatitude.Text = temp.Latitude;
            txtLongitude.Text = temp.Longitude;
            txtGPSDesc.Text = temp.GPSDesc;

            //txtManufacturer.Text = temp.Manufacturer;

            int _ManufacturerIndex = new DataAccess.tb_AlarminstrumentInfo().GetInstrumentList().Select(x => x.Manufacturer).Distinct().ToList().FindIndex(x => x.Equals(temp.Manufacturer));
            _CmbManufacturer.SelectedIndex = _ManufacturerIndex;

            int _SampingModIndex = RelationsLMP.Model.SystemEnum.EnumAlertorSampingModeToList().FindIndex(x => x.Item.Equals(temp.SampingMode));
            cmbSampingMode.SelectedIndex = _SampingModIndex;

            int _SubmitUnitIndex = new DataAccess.tb_SubmitUnit().GetSubmitUnitList().FindIndex(x => x.Name.Equals(temp.SubmitUnit));
            _CmbSubmitUnit.SelectedIndex = _SubmitUnitIndex;
            //cmbSubmitUnit.SelectedIndex = _SubmitUnitIndex;

            if (!string.IsNullOrEmpty(temp.ImageInfo))
            {
                Bitmap _bitmap = Static.Methods.GetImage(Model.SystemEnum.ImageType.Alarminstrument, temp.InstrumentId.ToString());
                if (_bitmap != null)
                {
                    SelectImage.PanelImage = _bitmap;
                }
                else
                    SelectImage.PanelImage = null;
            }

            dgvGasList.Rows.Clear();
            for (int i = 0; i < temp.GasInfoList.Count; i++)
            {
                dgvGasList.Rows.Add();
                dgvGasList.Rows[i].Tag = temp.GasInfoList[i];
                dgvGasList.Rows[i].Cells["GasName"].Value = temp.GasInfoList[i].Desc;
            }
        }

        private void InitControls()
        {
            dgvGasList.CellClick += DgvGasList_CellClick;

            okReturnToolbar21.Event_OKClick += OkReturnToolbar21_Event_OKClick;
            okReturnToolbar21.Event_ReturnClick += OkReturnToolbar21_Event_ReturnClick;

            SelectImage = new UC.SelectImage();
            SelectImage.Dock = DockStyle.Fill;
            grpImage.Controls.Add(SelectImage);

            InitComBoxGasType();
            InitComBoxSampingMode();

            _CmbSubmitUnit = new UC.ComboBox.SubmitUnit();
            _CmbSubmitUnit.Dock = DockStyle.Fill;
            pSubmitUnit.Controls.Add(_CmbSubmitUnit);

            _CmbManufacturer = new UC.ComboBox.Manufacturer();
            _CmbManufacturer.Dock = DockStyle.Fill;
            pManufacturer.Controls.Add(_CmbManufacturer);
        }

        private void OkReturnToolbar21_Event_ReturnClick(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void OkReturnToolbar21_Event_OKClick(object sender, EventArgs e)
        {
            try
            {

                if (new DataAccess.tb_TaskDetails().CheckIsExist(AlarminstrumentInfo.FactoryNumber))
                {
                    MessageBox.Show(this, "报警器已存在与任务列表中，无法进行修改！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtFactoryNumber.Text))
                {
                    txtFactoryNumber.Focus();
                    MessageBox.Show(this, "【出厂编号】不能为空！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (AlarminstrumentInfo.FactoryNumber != txtFactoryNumber.Text && new DataAccess.tb_AlarminstrumentInfo().CheckInstrumentIsExist(txtFactoryNumber.Text))
                {
                    txtFactoryNumber.Focus();
                    MessageBox.Show(this, "【出厂编号】已存在！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    string _Text = _CmbSubmitUnit.Text;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    _CmbSubmitUnit.Focus();
                    return;
                }


                AlarminstrumentInfo = new Model.DB.tb_AlarminstrumentInfo();

                List<Model.DB.tb_ParaInfo> _List = new List<Model.DB.tb_ParaInfo>();
                Model.DB.tb_ParaInfo _ParaInfoTemp;
                AlarminstrumentInfo.InstrumentName = txtInstrumentName.Text;
                AlarminstrumentInfo.FactoryNumber = txtFactoryNumber.Text;
                AlarminstrumentInfo.Model = txtModel.Text;
                AlarminstrumentInfo.ContractNo = txtContractNo.Text;

                //AlarminstrumentInfo.SubmitUnit = cmbSubmitUnit.Text;
                //AlarminstrumentInfo.Manufacturer = txtManufacturer.Text;

                AlarminstrumentInfo.SubmitUnit = _CmbSubmitUnit.Text;
                AlarminstrumentInfo.Manufacturer = _CmbManufacturer.Text;

                for (int i = 0; i < dgvGasList.Rows.Count; i++)
                {
                    _ParaInfoTemp = dgvGasList.Rows[i].Tag as Model.DB.tb_ParaInfo;
                    if (_ParaInfoTemp != null)
                    {
                        _List.Add(_ParaInfoTemp);
                    }
                }
                _List = _List.OrderBy(x => x.Id).ToList();

                string sGasList = string.Empty;
                //for (int i = 0; i < dgvGasList.Rows.Count; i++)
                //{
                //    _ParaInfoTemp = dgvGasList.Rows[i].Tag as Model.DB.tb_ParaInfo;
                //    if (_ParaInfoTemp != null)
                //    {
                //        sGasList += _ParaInfoTemp.Id.ToString() + "|";
                //    }
                //}

                for (int i = 0; i < _List.Count; i++)
                {

                    sGasList += _List[i].Id.ToString() + "|";
                }

                sGasList = sGasList.TrimEnd('|');
                AlarminstrumentInfo.GasTypeList = sGasList;
                AlarminstrumentInfo.SampingMode = (RelationsLMP.Model.SystemEnum.AlertorSampingMode)cmbSampingMode.SelectedValue;
                AlarminstrumentInfo.Longitude = txtLongitude.Text;
                AlarminstrumentInfo.Latitude = txtLatitude.Text;
                AlarminstrumentInfo.GPSDesc = txtGPSDesc.Text;

                if (string.IsNullOrWhiteSpace(AlarminstrumentInfo.InstrumentName))
                    AlarminstrumentInfo.InstrumentName = AlarminstrumentInfo.FactoryNumber;

                if (SelectImage.PanelImage != null)
                    AlarminstrumentInfo.ImageInfo = Relations.Common.Methods.ImageToBase64String((Bitmap)SelectImage.PanelImage);
                else
                    AlarminstrumentInfo.ImageInfo = string.Empty;

                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "保存报警器数据失败，错误信息：" + ex.Message, "异常信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DgvGasList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || !dgvGasList.Columns[e.ColumnIndex].Name.Equals("Delete")) return;
            Model.DB.tb_ParaInfo _ParaInfo = (Model.DB.tb_ParaInfo)dgvGasList.Rows[e.RowIndex].Tag;
            if (MessageBox.Show(this, string.Format("确定要删除此气体【{0}】吗？", _ParaInfo.Desc), "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                dgvGasList.Rows.RemoveAt(e.RowIndex);
            }
        }

        private void InitComBoxGasType()
        {
            List<Model.DB.tb_ParaInfo> _List = Static.ParaInfo.GasList;

            _List.Insert(0, new Model.DB.tb_ParaInfo() { Id = -1, Code = "null", Desc = "气体类型" });

            cmbGasType.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbGasType.DisplayMember = "Desc";
            cmbGasType.ValueMember = "Id";
            cmbGasType.DataSource = _List;
            if (cmbGasType.Items.Count > 0)
                cmbGasType.SelectedIndex = 0;

            cmbGasType.SelectedIndexChanged += CmbGasType_SelectedIndexChanged;
        }

        private void CmbGasType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbGasType.SelectedItem == null) return;
            Model.DB.tb_ParaInfo _ParaInfo = (Model.DB.tb_ParaInfo)cmbGasType.SelectedItem, _ParaInfoTemp;
            if (_ParaInfo == null || _ParaInfo.Id == -1) return;

            //if (Common.StaticInfo.ConfigInfo.CreateFactoryNumber)
            //    txtFactoryNumber.Text = InstrumentPluginInterface.CreateFactoryNumber(_ParaInfo);

            bool _Result = false;
            for (int i = 0; i < dgvGasList.Rows.Count; i++)
            {
                _ParaInfoTemp = (Model.DB.tb_ParaInfo)dgvGasList.Rows[i].Tag;
                if (_ParaInfoTemp.Id == _ParaInfo.Id)
                {
                    _Result = true;
                    break;
                }
            }
            if (!_Result)
            {
                dgvGasList.Rows.Add();
                dgvGasList.Rows[dgvGasList.Rows.Count - 1].Tag = _ParaInfo;
                dgvGasList.Rows[dgvGasList.Rows.Count - 1].Cells["GasName"].Value = _ParaInfo.Desc;
            }
            else
                MessageBox.Show(this, string.Format("该气体【{0}】已经存在！", _ParaInfo.Desc), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }


        private void InitComBoxSampingMode()
        {
            try
            {
                Static.Methods.InitComBox(ref cmbSampingMode, Model.SystemEnum.ComBoxType.SampleModel);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "初始化ComBoxSampingMode异常，错误信息：" + ex.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }
}
